package com.mec.web.y2012.coreservlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

public class MessageImage {
	
	private static final String SUFFIX_JPG = "jpg";

	public static BufferedImage makeMessageImage(String message, String fontName, int fontSize){
		Font font = new Font(fontName, Font.PLAIN, fontSize);
		//
		FontMetrics metrics = getFontMetrics(font);
		int messageWidth = metrics.stringWidth(message);
		//logger.info("messageWidth -> " + messageWidth);
		int baseLineX = messageWidth / 10;
		int width = messageWidth + 2*(baseLineX + fontSize);
		int height = fontSize * 7 /2;
		int baseLineY = height * 8 /10;
		
		//
		BufferedImage messageImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2d = (Graphics2D) messageImage.getGraphics();
		//
		g2d.setBackground(Color.WHITE);
		g2d.clearRect(0, 0, width, height);
		g2d.setFont(font);
		g2d.translate(baseLineX, baseLineY);
		g2d.setPaint(Color.LIGHT_GRAY);
		//
		
		AffineTransform origTransform = g2d.getTransform();
		g2d.shear(-0.95, 0);
		g2d.scale(1, 3);
		g2d.drawString(message, 0, 0);
		g2d.setTransform(origTransform);
		g2d.setPaint(Color.BLACK);
		g2d.drawString(message, 0, 0);
		//
		return messageImage;
		
	}
	public static void writeJPEG(BufferedImage image, OutputStream out){
		try{
			ImageIO.write(image, SUFFIX_JPG, out);
		}catch(IOException ioe){
			logger.error("Error outputting JPEG: ", ioe);
		}
	}
	
	public static void writeJPEG(BufferedImage image, File file){
		try{
			if(! file.exists()){
				file.createNewFile();
			}
			//
			ImageIO.write(image, SUFFIX_JPG, file);
		}catch(IOException ioe){
			logger.error("Error writing JPEG file: ", ioe);
		}
			
	}
	
	public static String[] getFontNames(){
		GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
		return env.getAvailableFontFamilyNames();
	}
	
	public static FontMetrics getFontMetrics (Font font){
		BufferedImage tempImage = 
				new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2d = (Graphics2D) tempImage.getGraphics();
		return g2d.getFontMetrics(font);
	}
	private static final Logger logger = 
			Logger.getLogger(MessageImage.class);
}
